import { getUserData, dayWeekMonthUser } from '@/api/app'

const state = {
  userData: [],
  userStatisticData: [{}, {}]
}

const mutations = {
  UPDATE_USER_DATA: (state, { data }) => {
    const labels = ['新增用户', '活跃用户', '总用户']
    const keys = ['addCounts', 'activeCounts', 'totalCounts']
    const buffer = []
    labels.forEach((item, index) => {
      const _item = {
        label: item,
        value: data[keys[index]]
      }
      buffer.push(_item)
    })
    state.userData = buffer
  },
  UPDATE_USER_STATISTIC_DATA: (state, { data, index }) => {
    const buffer = state.userStatisticData
    buffer[index] = data
    state.userStatisticData = buffer.concat()
  }
}

const actions = {
  async updateUserData ({ commit }, params) {
    try {
      const userData = await getUserData(params)
      commit('UPDATE_USER_DATA', userData)
    } catch (error) {
      console.error(error)
    }
  },
  async getUserStatisticData ({ commit }, { params, index }) {
    try {
      const keyword = index === 0 ? 'add' : 'active'
      const userStatisticData = await dayWeekMonthUser(params, keyword)
      if (userStatisticData.code === 200) {
        const data = {
          label: index === 0 ? '新增用户' : '活跃用户',
          value: userStatisticData.data
        }
        commit('UPDATE_USER_STATISTIC_DATA', { data, index })
      }
    } catch (error) {
      console.error(error)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
